#导入需要的模块
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
						                           
#准备数据
x=np.array([[19,30],[30,40],[39,47],[40,52],[47,50],[50,55],[60,60],[62,65],[73,70],[75,82],[77,85],[90,95],[92,90]])
y=np.array([0,0,0,0,0,0,1,1,1,1,1,1,1])
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=0)

#设置K值可选范围和误差率数组
k_range=range(2,11)		          #设置k值的取值范围
k_error=[]			          #保存预测误差率的数组

#开始验证K值
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score
for k in k_range:
    model=KNeighborsClassifier(n_neighbors=k)
    scores=cross_val_score(model,x,y,cv=5,scoring='accuracy')	
    k_error.append(1-scores.mean())

#画图.绘制各个K值所对应的预测误差率
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']='Simhei'
#plt.plot(k_range,k_error,'r-')
#plt.xlabel('k值')
#plt.ylabel('预测误差率')
#plt.show()

#得出结论：当K等于5或7时 误差率最低

x_pre = [[55,64]]

model1 =  KNeighborsClassifier(5)
model1.fit(x_train,y_train)
pred1 = model1.predict(x_pre)
print(f'k=5时,预测样本的分类结果为:{pred1}')

model2 = KNeighborsClassifier(7)
model2.fit(x_train,y_train)
pred2 = model1.predict(x_pre)
print(f'k=7时,预测样本的分类结果为:{pred2}')